document.addEventListener('DOMContentLoaded', function () {
    // 获取所有需要的DOM元素
    const apiSelect = document.getElementById('apiSelect');
    const methodDisplay = document.getElementById('methodDisplay');
    const methodBadge = document.getElementById('methodBadge');
    const baseUrl = document.getElementById('baseUrl');
    const paramsContainer = document.getElementById('paramsContainer');
    const bodyContainer = document.getElementById('bodyContainer');
    const requestBody = document.getElementById('requestBody');
    const finalUrl = document.getElementById('finalUrl');
    const sendRequest = document.getElementById('sendRequest');
    const responseStatus = document.getElementById('responseStatus');
    const responseBody = document.getElementById('responseBody');
    const responseHeaders = document.getElementById('responseHeaders');

    // 查询参数相关元素
    const queryParamsContainer = document.getElementById('queryParamsContainer');
    const queryParamsBody = document.getElementById('queryParamsBody');
    const addQueryParam = document.getElementById('addQueryParam');

    // JSON文件操作相关元素
    const jsonFileInput = document.getElementById('jsonFileInput');
    const loadJsonBtn = document.getElementById('loadJsonBtn');
    const saveJsonBtn = document.getElementById('saveJsonBtn');
    const currentFileName = document.getElementById('currentFileName');
    const customFileName = document.getElementById('customFileName');

    // ===== 1. JSON文件加载和保存功能 =====

    // 加载JSON文件按钮点击事件
    loadJsonBtn.addEventListener('click', function () {
        jsonFileInput.click();
    });

    // 替换现有的jsonFileInput事件监听器
    jsonFileInput.addEventListener('change', function (event) {
        const file = event.target.files[0];
        if (!file) {
            alert("未选择文件");
            return;
        }

        const reader = new FileReader();

        reader.onload = function (e) {
            const content = e.target.result;
            // 直接用原始DOM方法设置内容
            document.getElementById('requestBody').value = content;
        };

        reader.onerror = function () {
            alert("读取文件失败");
        };

        reader.readAsText(file);
    });



    // 保存为JSON文件
    saveJsonBtn.addEventListener('click', function () {
        if (!requestBody || !requestBody.value.trim()) {
            showToast("请求体为空，无法保存", "error");
            return;
        }

        try {
            // 检查JSON格式是否正确
            const jsonObj = JSON.parse(requestBody.value);

            // 创建Blob对象
            const blob = new Blob([JSON.stringify(jsonObj, null, 2)], {type: 'application/json'});

            // 创建有意义的默认文件名
            let fileName = 'request-body.json';

            // 从当前选择的API获取方法和路径
            if (apiSelect.value !== '') {
                const selectedOption = apiSelect.options[apiSelect.selectedIndex];
                const method = selectedOption.getAttribute('data-method').toLowerCase();
                const uri = selectedOption.getAttribute('data-uri');

                // 从URI提取第二个参数作为文件名
                const pathParts = uri.split('/').filter(part => part.length > 0);
                if (pathParts.length >= 2) {
                    // 使用第二个路径参数
                    const secondParam = pathParts[1].replace(/[{}]/g, '');
                    fileName = `${method}_${secondParam}.json`;
                } else if (pathParts.length === 1) {
                    // 只有一个路径参数的情况
                    fileName = `${method}_${pathParts[0]}.json`;
                } else {
                    // 没有路径参数的情况
                    fileName = `${method}_request.json`;
                }
            }

            // 如果用户已输入自定义文件名，则使用它
            if (customFileName && customFileName.value.trim()) {
                fileName = customFileName.value.trim() + '.json';
            }

            // 更新自定义文件名输入框的显示
            if (customFileName) {
                customFileName.value = fileName.replace('.json', '');
            }

            // 创建下载链接
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = fileName;

            // 触发下载
            document.body.appendChild(a);
            a.click();

            // 清理
            setTimeout(function () {
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            }, 0);

            showToast(`JSON文件已保存为 ${fileName}`, 'success');
        } catch (error) {
            showToast('JSON格式错误: ' + error.message, 'error');
        }
    });

    // ===== 2. 查询参数功能 =====

    // 添加查询参数
    if (addQueryParam) {
        addQueryParam.addEventListener('click', function () {
            addQueryParamRow();
        });
    }

    // 监听查询参数的变化
    if (queryParamsBody) {
        queryParamsBody.addEventListener('input', function (e) {
            if (e.target.classList.contains('query-param-input')) {
                updateFinalUrl();
            }
        });

        // 监听删除查询参数的事件
        queryParamsBody.addEventListener('click', function (e) {
            if (e.target.classList.contains('delete-param')) {
                e.target.closest('tr').remove();
                updateFinalUrl();
            }
        });
    }

    // 添加查询参数行的函数
    function addQueryParamRow() {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>
                <input type="text" class="form-control query-param-input query-param-name" placeholder="参数名">
            </td>
            <td>
                <input type="text" class="form-control query-param-input query-param-value" placeholder="参数值">
            </td>
            <td>
                <button class="delete-param">❌</button>
            </td>
        `;
        queryParamsBody.appendChild(row);
    }

    // 清空查询参数的函数
    function clearQueryParams() {
        if (queryParamsBody) {
            queryParamsBody.innerHTML = '';
        }
    }

    // ===== 3. API选择和参数处理 =====

    // 当选择API时
    apiSelect.addEventListener('change', function () {
        if (this.value === '') {
            methodDisplay.value = '';
            methodBadge.textContent = '-';
            methodBadge.style.backgroundColor = '#ccc';
            paramsContainer.innerHTML = `
                <label class="form-label">🔗 路径参数</label>
                <div class="text-muted mb-2 small">选择API后，此处将显示所需的路径参数</div>
            `;
            bodyContainer.style.display = 'none';
            if (queryParamsContainer) {
                queryParamsContainer.style.display = 'none'; // 隐藏查询参数
                clearQueryParams(); // 清空查询参数
            }
            finalUrl.value = '';
            sendRequest.disabled = true;
            return;
        }

        const selectedOption = this.options[this.selectedIndex];
        const method = selectedOption.getAttribute('data-method');
        const uri = selectedOption.getAttribute('data-uri');

        // 设置方法和样式
        methodDisplay.value = method;
        methodBadge.textContent = method;

        // 设置徽章颜色
        switch (method.toUpperCase()) {
            case 'GET':
                methodBadge.style.backgroundColor = '#4cc9f0';
                break;
            case 'POST':
                methodBadge.style.backgroundColor = '#3a86ff';
                break;
            case 'PUT':
                methodBadge.style.backgroundColor = '#ffc300';
                break;
            case 'DELETE':
                methodBadge.style.backgroundColor = '#ff006e';
                break;
            default:
                methodBadge.style.backgroundColor = '#6c757d';
        }

        // 处理路径参数
        paramsContainer.innerHTML = '<label class="form-label">🔗 路径参数</label>';
        const paramMatches = uri.match(/{([^}]+)}/g);
        if (paramMatches && paramMatches.length > 0) {
            paramMatches.forEach(match => {
                const paramName = match.replace(/{|}/g, '');
                const paramDiv = document.createElement('div');
                paramDiv.className = 'param-container';
                paramDiv.innerHTML = `
                    <label for="param_${paramName}" class="form-label">${paramName}</label>
                    <input type="text" id="param_${paramName}" class="form-control param-input" data-param="${paramName}">
                `;
                paramsContainer.appendChild(paramDiv);
            });
        } else {
            const noParamsDiv = document.createElement('div');
            noParamsDiv.className = 'text-muted mb-2';
            noParamsDiv.innerHTML = '此API没有路径参数';
            paramsContainer.appendChild(noParamsDiv);
        }

        // 根据请求方法决定显示请求体还是查询参数
        if (method.toUpperCase() === 'POST') {
            bodyContainer.style.display = 'block';
            if (queryParamsContainer) {
                queryParamsContainer.style.display = 'none'; // POST请求隐藏查询参数
                clearQueryParams(); // 清空查询参数
            }
        } else if (method.toUpperCase() === 'GET') {
            bodyContainer.style.display = 'none';
            if (queryParamsContainer) {
                queryParamsContainer.style.display = 'block'; // GET请求显示查询参数
                // 确保至少有一个查询参数行
                if (queryParamsBody && queryParamsBody.children.length === 0) {
                    addQueryParamRow();
                }
            }
        } else {
            bodyContainer.style.display = 'none';
            if (queryParamsContainer) {
                queryParamsContainer.style.display = 'none'; // 其他请求隐藏查询参数
                clearQueryParams(); // 清空查询参数
            }
        }

        // 当选择新API时，更新默认文件名
        if (customFileName) {
            const pathParts = uri.split('/').filter(part => part.length > 0);
            let fileName = 'request';

            if (pathParts.length >= 2) {
                // 使用第二个路径参数
                const secondParam = pathParts[1].replace(/[{}]/g, '');
                fileName = secondParam;
            } else if (pathParts.length === 1) {
                // 只有一个路径参数的情况
                fileName = pathParts[0];
            }

            customFileName.value = `${method.toLowerCase()}_${fileName}`;
        }

        // 启用发送按钮
        sendRequest.disabled = false;

        // 更新最终URL
        updateFinalUrl();
    });

    // 当基础URL改变时更新最终URL
    baseUrl.addEventListener('input', updateFinalUrl);

    // 监听参数输入变化
    paramsContainer.addEventListener('input', function (e) {
        if (e.target.classList.contains('param-input')) {
            updateFinalUrl();
        }
    });

    // 更新最终URL
    function updateFinalUrl() {
        if (apiSelect.value === '') {
            finalUrl.value = '';
            return;
        }

        const selectedOption = apiSelect.options[apiSelect.selectedIndex];
        let uri = selectedOption.getAttribute('data-uri');

        // 替换路径参数
        const inputs = paramsContainer.querySelectorAll('.param-input');
        inputs.forEach(input => {
            const paramName = input.getAttribute('data-param');
            const paramValue = input.value || `{${paramName}}`;
            uri = uri.replace(`{${paramName}}`, paramValue);
        });

        // 构建基本URL
        let url = baseUrl.value + uri;


        // 添加查询参数
        const method = methodDisplay.value;
        if (method.toUpperCase() === 'GET' && queryParamsBody) {
            const queryParams = [];
            const queryRows = queryParamsBody.querySelectorAll('tr');

            queryRows.forEach(row => {
                const nameInput = row.querySelector('.query-param-name');
                const valueInput = row.querySelector('.query-param-value');

                if (nameInput && valueInput && nameInput.value.trim()) {
                    queryParams.push(`${encodeURIComponent(nameInput.value)}=${encodeURIComponent(valueInput.value)}`);
                }
            });

            if (queryParams.length > 0) {
                url += `?${queryParams.join('&')}`;
            }
        }

        finalUrl.value = url;
    }

    // ===== 4. 发送请求功能 =====

    // 发送请求
    sendRequest.addEventListener('click', function () {
        const method = methodDisplay.value;
        const url = finalUrl.value;

        // 检查是否有未填写的参数
        if (url.includes('{')) {
            alert('请填写所有路径参数！');
            return;
        }

        // 准备请求体
        let body = null;
        if (method.toUpperCase() === 'POST' && requestBody.value.trim()) {
            try {
                body = JSON.parse(requestBody.value);
            } catch (e) {
                alert('请求体必须是有效的JSON格式！');
                return;
            }
        }

        // 发送到服务器代理
        responseStatus.innerHTML = `
            <div class="alert alert-info">
                <div class="loading-spinner"></div>
                正在发送请求...
            </div>
        `;

        fetch('/proxy', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                method: method,
                url: url,
                body: body,
                headers: {'Content-Type': 'application/json'}
            })
        })
            .then(response => response.json())
            .then(data => {
                // 显示状态码
                const statusCode = data.status;
                let statusClass = 'success';
                let statusIcon = 'fa-check-circle';

                if (statusCode >= 400) {
                    statusClass = 'danger';
                    statusIcon = 'fa-times-circle';
                } else if (statusCode >= 300) {
                    statusClass = 'warning';
                    statusIcon = 'fa-exclamation-circle';
                }

                responseStatus.innerHTML = `
                <div class="alert alert-${statusClass}">
                    <i class="fas ${statusIcon}"></i>
                    状态码: ${statusCode}
                </div>
            `;

                // 显示响应体
                if (data.is_json) {
                    responseBody.textContent = JSON.stringify(data.body, null, 2);
                } else {
                    responseBody.textContent = data.body;
                }

                // 显示响应头
                responseHeaders.textContent = JSON.stringify(data.headers, null, 2);
            })
            .catch(error => {
                responseStatus.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    请求失败: ${error.message}
                </div>
            `;
            });
    });

    // ===== 5. 辅助函数 =====

    // 显示提示消息
    function showToast(message, type = 'info') {
        // 创建toast元素
        const toast = document.createElement('div');
        toast.className = `toast-message toast-${type}`;
        toast.textContent = message;

        // 添加到页面
        document.body.appendChild(toast);

        // 淡入
        setTimeout(() => {
            toast.classList.add('show');
        }, 10);

        // 3秒后淡出
        setTimeout(() => {
            toast.classList.remove('show');
            // 移除元素
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 300);
        }, 3000);
    }

    // ===== 6. 调试辅助 =====

    // 添加调试按钮（可选，可以在最终代码中移除）
    // /*
    const debugBtn = document.createElement('button');
    debugBtn.textContent = '调试JSON';
    debugBtn.style.position = 'fixed';
    debugBtn.style.bottom = '10px';
    debugBtn.style.right = '10px';
    debugBtn.style.zIndex = '9999';
    debugBtn.className = 'btn btn-sm btn-outline-secondary';

    debugBtn.addEventListener('click', function () {
        console.log('请求体元素:', requestBody);
        console.log('请求体值:', requestBody.value);
        console.log('当前文件名:', currentFileName.textContent);
    });

    document.body.appendChild(debugBtn);
    // */
});
